<template>
  <div class='ele-body ele-body-card'>
    <a-divider>版本升级</a-divider>
    <a-card
      :bordered='true'
      :body-style="{padding: '20px'}">
      <a-form
        ref='ipPortformRef'
        :model='ipPortformModel'
        :rules="ipPortRules"
        :label-col='{ md: { span: 7 }, sm: { span: 24 } }'
        :wrapper-col='{ md: { span: 17 }, sm: { span: 24 } }'
        @submit='setIpPortActionToCmdQueue'
      >

        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label='当前版本:' name='clientVersion'>
              <a-input v-model:value='ipPortformModel.clientVersion' :disabled='true' allow-clear autocomplete='off' style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :md='12' :sm='24' :xs='24'/>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-form-item label="所属目标版本:" name="upgradeTo">
              <a-select
                show-search
                v-model:value="ipPortformModel.upgradeTo"
                placeholder="请选择所属目标版本"
                style="width: 100%"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
              >
                <a-select-option v-for="item in firmwareList" :key="item.softwareId" >
                  升级到版本：{{ item.version }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='12' :sm='24' :xs='24'/>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='5' :sm='24' :xs='24'>
            <a-button type='primary' html-type='submit' :loading='ipPortformRefLoading' v-permission="['PROPERTY_DEVICELIST_MGR_SPRAYCAMERA_SOFTWARE_Upgrade_BUTTON']">
              升级
            </a-button>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
            <a-button type='primary' html-type='button' @click="syncToSomeOxtall()" v-permission="['PROPERTY_DEVICELIST_MGR_SPRAYCAMERA_SOFTWARE_Upgrade2OXTALL_BUTTON']">
              升级相同牛舍下的所有设备
            </a-button>
          </a-col>
          <a-col :md='7' :sm='24' :xs='24' />
        </a-row>
      </a-form>
    </a-card>

  </div>
</template>

<script>
import {DeviceCommandDownQueueApi} from '@/api/property/DeviceCommandDownQueueApi';
import { message } from 'ant-design-vue';
import {DeviceSprayCameraSoftwareApi} from "@/api/property/spraycamera/DeviceSprayCameraSoftwareApi";
import {DeviceCommandTemplateDistributeApi} from "@/api/property/DeviceCommandTemplateDistributeApi";
export default {
  name: 'DeviceSpraycameraUpgrade',
  components: {
  },
  props: {
    data: Object
  },
  async created() {
    await this.init();
  },
  data() {
    return {
      loading : false,

      sourceConfig : {},
      ipPortformModel: {},
      ipPortRules : {},
      ipPortformRefLoading: false,
      ipPortformRefTimer : undefined,

      firmwareList : []
    };
  },
  methods: {
    async init() {

      let firmwareList = await DeviceSprayCameraSoftwareApi.list({})
      this.firmwareList = (firmwareList ? firmwareList.data : null) || [];
      this.ipPortformModel.clientVersion = this.data.clientVersion;
    },
    checkProcess(sceneDictate, clearCallback, callback) {
      let params = {
        recordId: this.data.recordId,
        sceneDictate: sceneDictate
      };
      let result = DeviceCommandDownQueueApi.workingDetail(params);
      result
        .then(result => {
          if (!result || !result.dcdqId) { //处理完成了
            clearCallback && clearCallback(); //去掉菊花+清除循环调用
            callback && callback(); //用户自定义
          }
        })
        .catch(() => {
          clearCallback && clearCallback(); //去掉菊花+清除循环调用
        });
    },


    //设置域名 begin
    clearIpPortformRef() {
      this.ipPortformRefLoading = false;
      clearInterval(this.ipPortformRefTimer);
    },
    checkIpPort() {
      let that = this;
      this.checkProcess(6, this.clearIpPortformRef, function () {
        that.init();
      });
    },
    setIpPortActionToCmdQueue() {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 6
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushIpPort();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },

    pushIpPort() {
      if (!this.ipPortformModel.upgradeTo) {
        message.error('请先选择版本');
        return;
      }

      this.loading = true;
      let updateDataRecord = {
        updateData: JSON.stringify({
          old: this.sourceConfig,
          update: this.ipPortformModel
        }),
        recordId: this.data.recordId,
        templateCode: 'spraycamera',
        dictate: 6,
        sceneDictate: 6
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.ipPortformRefLoading = true; //转圈
          this.ipPortformRefTimer = setInterval(this.checkIpPort, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //设置域名 end


    syncToSomeOxtall() {
      if (this.data.oxtId <= 0) {
        message.error('当前牛舍没有其他牛舍');
        return;
      }
      let that = this;
      this.loading = true;
      // 格式化时间段数据为JSON字符串
      const formData = {
        "upgradeTo" : this.ipPortformModel.upgradeTo,
      };
      let toObjs = {
        "oxtall_ids" : [that.data.oxtId]
      };
      let addParams = {
        "templateCode" : "spraycamera",
        "toObjs" : JSON.stringify(toObjs),
        "sceneDictate" : 6,
        "dictate" : 6,
        "templateContent" :  JSON.stringify(formData)
      };
      let result2 = DeviceCommandTemplateDistributeApi.add(addParams);
      result2.then(res => {
        // 移除加载框
        that.loading = false;
        // 提示添加成功
        message.success(res.message);
      })
        .catch(() => {
          that.loading = false;
        });
    },


  }
};
</script>
<style scoped>
/** 用户卡片 */
.workplace-user-card .ele-cell-content {
  overflow: hidden;
}

.workplace-user-card h4 {
  margin-bottom: 6px;
}
</style>
